package com.github.florent37.rxretrojsoup.tutosohosfrance;

import com.github.florent37.rxretrojsoup.ResourceTable;
import com.isotne.glidelibrary.utils.OhosGlide;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.io.IOException;
import java.util.List;

public class ListItemProvider extends BaseItemProvider {
    private List<Article> list;
    private AbilitySlice slice;
    public ListItemProvider(List<Article> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }
    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }
    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()){
            return list.get(position);
        }
        return null;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_cell_article, null, false);
        } else {
            cpt = convertComponent;
        }
        Article sampleItem = list.get(position);
        Text textTitle = (Text) cpt.findComponentById(ResourceTable.Id_title);
        Text textUrl = (Text) cpt.findComponentById(ResourceTable.Id_url);
        Image image = (Image) cpt.findComponentById(ResourceTable.Id_image);
        textTitle.setText(sampleItem.title);
        textUrl.setText(sampleItem.description);
        if(sampleItem.image!= null) {
            try {
                OhosGlide.with(slice).load(sampleItem.image).def(ResourceTable.Media_icon).into(image);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cpt;
    }
}